/*
 * @Author: egg1bro
 * @Date: 2023-01-03 17:24:09
 * @LastEditTime: 2023-02-21 15:00:29
 * @LastEditors: egg1bro
 * @Description: 
 * @FilePath: \team-design-backend\controller\admin.js
 * 可以输入预定的版权声明、个性签名、空行等
 */
// 引入连接池
const db = require('../db')

// 阿里短信
const Core = require('@alicloud/pop-core');

const jwt = require('jsonwebtoken')
const auth = require('../controller/auth');
const pool = require('../db');
// 验证码默认值
let smsCode = null

// 获取用户信息
const getUserInfo = (req, res) => {
    // req.auth为jwt中定义的payload的值
    console.log(req.auth, '解析token值');
    // console.log(req.headers, '222');
    db.query('SELECT * FROM users WHERE user_id = ?', [req.auth.user_id], (err, results) => {
        if (err) {
            return res.status(500).json({
                code: 500,
                msg: '用户信息获取失败',
                data: null
            })
        }
        console.log(results, '用户信息');
        res.send({
            status: 200,
            message: '获取用户信息成功！',
            data: results[0], // 要发送给客户端的用户信息
        })
    })
}

// 更新用户姓名
const updateUserName = (req, res) => {
    let user_name = req.body.user_name
    console.log(req.body);
    db.query('UPDATE `users` SET `user_name`= ? WHERE `user_id`= ?', [user_name, req.auth.user_id], (err, results) => {
        // console.log(err);
        // console.log(req.auth);
        if (err) {
            return res.status(500).json({
                code: 500,
                msg: '更改用户姓名失败',
                data: null
            })
        }

        res.send({
            status: 200,
            message: '更改用户姓名成功！',
            data: null
        })
    })
}

// 更新用户签名
const updateUserDesc = (req, res) => {
    let user_desc = req.body.user_desc

    db.query('UPDATE `users` SET `user_desc`= ? WHERE `user_id`= ?', [user_desc, req.auth.user_id], (err, results) => {
        // console.log(err);
        // console.log(req.auth);
        if (err) {
            return res.status(500).json({
                code: 500,
                msg: '更改用户签名失败',
                data: null
            })
        }

        res.send({
            status: 200,
            message: '更改用户签名成功！',
            data: null
        })
    })
}

// 更新用户性别
const updateUserSex = (req, res) => {
    let user_sex = req.body.user_sex
    db.query('UPDATE `users` SET `user_sex`= ? WHERE `user_id`= ?', [user_sex, req.auth.user_id], (err, results) => {
        console.log(err);
        // console.log(req.auth);
        if (err) {
            return res.status(500).json({
                code: 500,
                msg: '更改用户性别失败',
                data: null
            })
        }

        res.send({
            status: 200,
            message: '更改用户性别成功！',
            data: null
        })
    })
}

// 获取验证码(token)
const getSmsByToken = (req, res) => {
    const phone = req.query.phone
    console.log(req.query, 'query');
    // console.log(phone);
    smsCode = Math.floor(Math.random() * 900000) + 100000;
    console.log(smsCode, '发sms');
    if (phone) {
        var client = new Core({
            accessKeyId: 'LTAI5t6QWxyoNAm9qY1U9D9h',
            accessKeySecret: 'E36W2GDrX06dO1BNqB1H0HlHSUAdK3',
            // securityToken: '<your-sts-token>', // use STS Token
            endpoint: 'https://dysmsapi.aliyuncs.com',
            apiVersion: '2017-05-25'
        });

        var params = {
            "SignName": "eggbro提醒您",
            "TemplateCode": "SMS_268240019",
            "PhoneNumbers": phone,
            "TemplateParam": `{"code":'${smsCode}'}`
        }

        var requestOption = {
            method: 'POST',
            formatParams: false,
        };


        client.request('SendSms', params, requestOption).then((result) => {
            if (result.Code == 'OK') {
                return res.status(200).json({
                    code: 200,
                    msg: '发送验证码成功',
                    data: smsCode
                })
            }
        }).catch(err => {
            console.log(err);
            res.status(200).json({
                code: 404,
                msg: '验证码发送失败',
                data: null
            })
        })
    } else {
        res.status(200).json({
            code: 404,
            msg: '请输入手机号',
            data: null
        })
    }
}

//验证前台返回的验证码去更改绑定手机账号
const verifySmsToUpdatePhoneByToken = (req, res) => {
    const { sms, phone } = req.body
    console.log(sms, '验证Sms');
    console.log(req.auth);
    if (smsCode = sms) {
        db.query('UPDATE `users` SET `user_phone`= ? WHERE `user_id`= ?', [phone, req.auth.user_id], (err, results) => {
            if (err) {
                return res.status(200).json({
                    code: 404,
                    msg: '服务器出错！',
                    data: null
                })
            }
            res.status(200).json({
                code: 200,
                msg: '修改手机号成功',
                data: null
            })
        })
    } else {
        res.status(200).json({
            code: 404,
            msg: '验证码错误',
            data: null
        })
    }
}

// 验证前台返回的验证码去reset用户密码
const verifySmsToResetPasswordPage = (req, res) => {
    const { sms } = req.body
    console.log(sms, '验证Sms');
    if (sms) {
        if (smsCode == sms) {
            return res.status(200).json({
                code: 200,
                msg: '验证码正确',
                data: null
            })
        } else {
            return res.status(200).json({
                code: 400,
                msg: '验证码错误，请重新输入',
                data: null
            })
        }
    } else {
        res.status(200).json({
            code: 400,
            msg: '请输入验证码',
            data: null
        })
    }

}

// update用户密码(输入用户旧密码和新密码)
const updateUserPassword = (req, res) => {
    const { newPassword, password } = req.body
    console.log(req.body,'updateUserPassword');
    // 新旧密码都存在
    if (newPassword && password) {
        // 校验原密码是否正确
        db.query('SELECT * FROM users WHERE user_password = ? AND user_id = ?', [password, req.auth.user_id], (err, results) => {
            if (err) {
                return res.status(200).json({
                    code: 404,
                    msg: '服务器错误',
                    data: null
                })
            }
            if (results.length > 0) {
                db.query('UPDATE `users` SET `user_password`= ? WHERE `user_id`= ?', [newPassword, req.auth.user_id], (err, results) => {
                    if (err) {
                        return res.status(200).json({
                            code: 404,
                            msg: '服务器错误',
                            data: null
                        })
                    }
                    res.status(200).json({
                        code: 200,
                        msg: '修改用户密码成功',
                        data: null
                    })
                })
            } else {
                // 密码不正确
                res.status(200).json({
                    code: 404,
                    msg: '请输入正确的用户密码',
                    data: null
                })
            }
        })
    } else {
        return res.status(200).json({
            code: 404,
            msg: '请输入完整的信息',
            data: null
        })
    }
}

// 重置用户密码(通过手机验证码验证后直接修改密码)
const resetUserPassword = (req, res) => {
    let { password } = req.body
    db.query('UPDATE `users` SET `user_password`= ? WHERE `user_id`= ?', [password, req.auth.user_id], (err, results) => {
        if (err) {
            return res.status(200).json({
                code: 404,
                msg: '服务器错误',
                data: null
            })
        }

        res.status(200).json({
            code: 200,
            msg: '重置用户密码成功',
            data: null
        })
    })
}

// 账号注销
const accountCancell = (req, res) => {
    console.log(req.auth);
    db.query('DELETE FROM users WHERE user_id = ?',[req.auth.user_id],(err,results) => {
        if (err) {
            return res.status(200).json({
                code: 404,
                msg: '服务器错误',
                data: null
            })
        } else {
            res.status(200).json({
                code: 200,
                msg: '用户注销成功',
                data: null
            })
        }
    })
}

// 获取验证码
module.exports = {
    getUserInfo,
    updateUserName,
    updateUserDesc,
    updateUserSex,
    getSmsByToken,
    verifySmsToUpdatePhoneByToken,
    verifySmsToResetPasswordPage,
    resetUserPassword,
    updateUserPassword,
    accountCancell
}